package cn.sockstack.controller;

import cn.sockstack.entity.Communities;
import cn.sockstack.service.CommunityService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class IndexController {
    @Autowired
    CommunityService communityService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping(value = "/")
    public String index(
            Model model,
            @RequestParam(value = "page", defaultValue = "1") int page,
            HttpSession session
    ) {
        Object username = session.getAttribute("username");
        String user_name = String.valueOf(username);
        if (user_name != null) {
            model.addAttribute("username", user_name);
        } else {
            model.addAttribute("username", "");
        }

        model.addAttribute("name", "ok");
        PageHelper.startPage(page, 1);
        List<Communities> communities = communityService.findAll();
        model.addAttribute("communities", communities);

        return "index";
    }

    @GetMapping(value = "redis_set")
    @ResponseBody
    public String redis(@RequestParam(value = "data", defaultValue = "ok") String data) {
        redisTemplate.opsForValue().set("key", data);
        return "ok";
    }

    @GetMapping(value = "redis_get")
    @ResponseBody
    public String redis_get() {
        String value = redisTemplate.opsForValue().get("key");

        return value;
    }
}
